package com.codingapi.websocket.demo.service.impl;

import com.codingapi.websocket.core.client.WebSocketSession;
import com.codingapi.websocket.core.handler.SimpleWebSocketHandler;
import com.codingapi.websocket.demo.entity.Message;
import com.codingapi.websocket.demo.service.MessageService;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author modificial
 * @date 2018/8/9
 * @company codingApi
 * @description
 */
@Service
public class MessageServiceImpl implements MessageService {
    /**
     * 打印日志
     */
    private static  final Logger LOGGER=LoggerFactory.getLogger(MessageServiceImpl.class);
    @Override
    public boolean send(Message message) {
     Map<String,WebSocketSession> map=SimpleWebSocketHandler.getSocketMap();
        LOGGER.info("websocket---------"+map);
     if(message!=null){
         String id=message.getId();
         if(map.containsKey(id)) {
             WebSocketSession webSocketSession = map.get(id);
             TextWebSocketFrame textWebSocketFrame=new TextWebSocketFrame(message.getData());
              webSocketSession.sendMessage(textWebSocketFrame);
             return  true;
         }else {
             LOGGER.error("不包含该商家id");
             throw new RuntimeException("不包含该商家id");
         }
     }
     return false;
    }
}
